package info.batcloud.fanli.admin.controller;

import com.ctospace.archit.common.pagination.Paging;
import info.batcloud.fanli.admin.vo.AuthorizeVo;
import info.batcloud.fanli.core.dto.UserDTO;
import info.batcloud.fanli.core.enums.UserLevel;
import info.batcloud.fanli.core.helper.StringHelper;
import info.batcloud.fanli.core.service.UserAuthorizeService;
import info.batcloud.fanli.core.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Inject
    private UserService userService;

    @Inject
    private UserAuthorizeService userAuthorizeService;

    @GetMapping("/authorize-by-phone")
    public Object findAuthorizeByPhone(@RequestParam String phone) {
        Map<String, Object> map = new HashMap<>();
        UserDTO userDTO = userService.findByPhone(phone);
        map.put("user", userDTO);
        map.put("authorizeList", userDTO == null ? new ArrayList() : userAuthorizeService.findByUserId(userDTO.getId()).stream().map(o -> {
            AuthorizeVo av = new AuthorizeVo();
            av.setAuthorize(o);
            return av;
        }).collect(Collectors.toList()));
        return map;
    }

    @GetMapping("/export")
    public Object export(UserService.ExportParam param, HttpServletResponse response) throws IOException {
        File file = userService.exportUser(param);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String fileName = URLEncoder.encode("用户", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName + System.currentTimeMillis() + ".xls");
        try (InputStream is = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            file.delete();
        }
        return null;
    }


    @GetMapping("/find-by-phone")
    public Object findByPhone(@RequestParam String phone) {
        Map<String, Object> map = new HashMap<>();
        UserDTO userDTO = userService.findByPhone(phone);
        userDTO.setPhone(StringHelper.protect(userDTO.getPhone()));
        map.put("user", userDTO == null ? new UserDTO() : userDTO);
        return map;
    }

    @PutMapping("/level/{userId}")
    public Object setUserLevel(@PathVariable long userId, @RequestParam UserLevel level) {
        userService.setUserLevel(userId, level);
        return true;
    }

    @GetMapping("/search")
    public Object search(UserService.SearchParam param) {
        Paging<UserDTO> paging = userService.search(param);
        paging.setResults(paging.getResults().stream().map(u -> {
            u.setPhone(StringHelper.protect(u.getPhone()));
            return u;
        }).collect(Collectors.toList()));
        return paging;
    }

    @PutMapping("/lock/{userId}-{lock}")
    public Object lock(@PathVariable long userId, @PathVariable boolean lock) {
        userService.lockUser(userId, lock);
        return true;
    }

    @DeleteMapping("/del/{userId}")
    public Object lock(@PathVariable long userId) {
        userService.deleteUser(userId);
        return true;
    }
}
